﻿package top.yangyitao.util;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import com.sun.mail.util.MailSSLSocketFactory;


/**
 * smtp发送邮件
 * 默认开启SSL加密传输
 * @param from发送邮件的邮箱
 * @param fromPWD 发送邮箱的密码
 * @param fromServerHost from邮箱的服务器地址
 * @param fromServerrPort from邮箱的服务器的smtp端口号
 * @author Shinelon
 *
 */
public class EmailManager {
	private static final String from = "ee_tal@zoho.com.cn";
	private static final String fromPWD = "1183609515";
	private static final String fromServerHost = "smtp.zoho.com.cn";
	private static final int fromServerPort = 465;
	private static final transient Properties properties;
	private static transient Session session;
	static {
		properties = new Properties();
		properties.put("mail.transport.protocol", "smtp");
		properties.put("mail.smtp.auth","true");
		MailSSLSocketFactory mailSSLSocketFactory = null;
		try {
			mailSSLSocketFactory = new MailSSLSocketFactory();
		} catch (GeneralSecurityException e) {
			e.printStackTrace();
		}
		mailSSLSocketFactory.setTrustAllHosts(true);
		properties.put("mail.smtp.ssl.enable", "true");
		properties.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
		session = Session.getInstance(properties);
		session.setDebug(true);
	}
	/**
	 * 
	 * @param rec_userName 收件人
	 * @param subject 邮件主题
	 * @param content邮件内容
	 * @throws AddressException
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException 
	 */
	public static void sendEmail(String rec_userName,String subject,String content) throws Exception {
		MimeMessage mimeMessage = new MimeMessage(session);
		mimeMessage.setFrom(new InternetAddress(from));
		mimeMessage.setSubject(subject,"UTF-8");
		mimeMessage.setContent(content,"text/html;charset=UTF-8");
        mimeMessage.setSentDate(new Date()); 
        mimeMessage.addRecipient(RecipientType.TO, new InternetAddress(rec_userName) );
        Transport transport = session.getTransport();
        transport.connect(fromServerHost, fromServerPort, from, fromPWD);
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); 
        transport.close();
	}
}
